package com.epoint.springsecuritylearning.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.epoint.springsecuritylearning.exception.LoginUserDetails;
import com.epoint.springsecuritylearning.exception.UserNullException;
import com.epoint.springsecuritylearning.user.domain.SysUser;
import com.epoint.springsecuritylearning.user.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;

/**
 * 通过前端输入的username来查询我们库里面的真实用户信息
 *
 * 一般我们数据是存入mysql中
 */
@Component
public class MyUserServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("login_name", username);
        SysUser sysUser = sysUserMapper.selectOne(userQueryWrapper);

        if(sysUser == null){
            throw new UserNullException("用户名密码输入错误!");
        }

        /**
         * 正规的做法还是使用 RBAC 模型去建立一套权限体系
         * 主体3个： 用户、角色、权限，和项目管理的逻辑一摸一样
         * 用户-》角色（N：N） =》 关联表
         * 角色-》权限（N：N）=》  关联表
         *
         * 这里我为了图方便就随便写2个
         */
        LoginUserDetails loginUserDetails = new LoginUserDetails(sysUser,
                new HashSet<String>(Arrays.asList("system:inspection:add", "system:inspection:list")));
        return loginUserDetails;
    }
}
